<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { useRouter } from 'vue-router'
import ws from '@/services/websocket'
import { useUserStore } from '@/stores/user'
import { usePropertyStore } from '@/stores/property'

const router = useRouter()
const userStore = useUserStore()
const propertyStore = usePropertyStore()
const username = ref('')
const password = ref('')
const loginMsg = ref('')

function goRegist() {
  router.push('/login/regist')
}
//登录按钮的回调函数
function submitLogin() {
  const payload = {
    genre: 1,
    type: 'login',
    username: username.value,
    password: password.value,
  }
  ws.send(JSON.stringify(payload))
}
//服务器返回登录的回调函数
function handleLoginResponse(message) {
  // 期望格式：{ genre: 1, type: 'login', state: 0|1, uid?: number }
  if (Number(message.state) === 0) {
    userStore.setUid(message.uid)
    console.log("用户登录成功！",userStore.uid)
    //登录成功
    loginMsg.value = "登录成功！正在获取用户信息";
    // 后续页面跳转由上层控制或此处跳转
    // 登录成功后，请求玩家信息
    try {
      ws.send(JSON.stringify({ genre: 2, type: 'getinfo', uid: message.uid }))
    } catch (_) {}
  } else {
    // 登录失败，后续可添加错误提示
    console.log("用户登录失败！")
    loginMsg.value = message.message && typeof message.message === 'string' ? message.message : '';
  }
}
//服务器返回玩家信息的回调函数
function handleGetInfoResponse(message) {
  // 期望格式：{ genre:2, type:'getinfo', state:0, data:{ property:{...}, information:{...} } }
  if (Number(message.state) !== 0 || !message.data) return
  const data = message.data || {}
  const info = data.information || {}
  const prop = data.property || {}
  //console.log("info和prop",info,prop)
  // 更新用户信息
  if (typeof info.nickname === 'string') userStore.setNickename(info.nickname)
  if (typeof info.profile === 'string') userStore.setProfile(info.profile)
  if (typeof info.grade === 'number') userStore.setGrade(info.grade)
  if (typeof info.experience === 'number') userStore.setExperience(info.experience)
  //console.log("玩家基本信息：用户名：",userStore.nickename, "头像：",userStore.profile)
  // 更新资产
  if (prop.gold != null) propertyStore.setGold(prop.gold)
  if (prop.soul != null) propertyStore.setSoul(prop.soul)
  if (prop.box1 != null) propertyStore.setBox1(prop.box1)
  if (prop.box2 != null) propertyStore.setBox2(prop.box2)
  if (prop.extra1 != null) propertyStore.setExtra1(prop.extra1)
  if (prop.extra2 != null) propertyStore.setExtra2(prop.extra2)
  if (prop.extra3 != null) propertyStore.setExtra3(prop.extra3)
  if (typeof prop.charactor === 'string') {
    // 解析 charactor 字符串，将每一位转换为布尔值
    const charactorData = prop.charactor.split('').map(char => char === '1')
    propertyStore.setCharactorData(charactorData)
    console.log('charactor_data:', charactorData)
  }
  //console.log("玩家资产：金锭：",propertyStore.gold , "魂玉：",propertyStore.soul,"角色",propertyStore.charactor)
  loginMsg.value = "用户信息获取成功，请稍后！";
  setTimeout(() => {
    router.replace('/main')
  }, 1000)
}
//在挂载的时候注册网络相关的回调函数
onMounted(() => {
  ws.on(1, 'login', handleLoginResponse)
  ws.on(2, 'getinfo', handleGetInfoResponse)
})

//在卸载的时候注销网络相关的回调函数
onBeforeUnmount(() => {
  ws.off(1, 'login')
  ws.off(2, 'getinfo')
})
</script>

<template>
  <div class="form">
    <h2>登录</h2>
    <label>
      用户名
      <input v-model.trim="username" placeholder="请输入用户名" />
    </label>
    <label>
      密码
      <input type="password" v-model.trim="password" placeholder="请输入密码" />
    </label>
    <button class="primary" @click="submitLogin">登录</button>
    <button class="link" @click="goRegist">去注册</button>
    <p v-if="loginMsg" class="msg">{{ loginMsg }}</p>
  </div>
  
</template>

<style scoped>
.form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
label {
  display: flex;
  flex-direction: column;
  gap: 6px;
  font-size: 14px;
}
input {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
}
button.primary {
  margin-top: 8px;
  padding: 10px 12px;
  background: #1677ff;
  color: #fff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}
button.link {
  padding: 8px 0;
  background: transparent;
  color: #1677ff;
  border: none;
  cursor: pointer;
}
.msg {
  margin-top: 8px;
  color: #333;
  text-align: center;
}
</style>


